var rootPath = getRootPath();
var currentPagNo = 1;
$(function() {
	$('#userIntegralTable').DataTable({
        "language": {
        	"lengthMenu": "每页 _MENU_ 条记录",
            "zeroRecords": " ",
            "info": "当前 _START_ 条到 _END_ 条 &nbsp;&nbsp;&nbsp;共 _TOTAL_ 条记录",
            "infoEmpty": "无记录",
            "infoFiltered": "",//(从 _MAX_ 条记录过滤)
            "search": "搜索",
            "processing": "<font color='red'>载入中...</font>",
            "paginate": {
                "first": "首页",
                "previous": "上一页",
                "next": "下一页",
                "last": "尾页"
            }
        },
        serverSide: true,
        info: true,
        lengthChange: false,//是否允许用户改变表格每页显示的记录数
        ordering: false,//是否允许用户排序
        paging: true,//是否分页
        processing: true,
        searching: false,
        pagingType: "simple_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
        stateSave: true,//刷新时是否保存状态
        autoWidth: true,//自动计算宽度
        orderMulti: true,
        pageLength: 10,
        fnInitComplete:function(){//创建完成回调缩略图创建
        	//$('.galpop').galpop();
        },
		"ajax" : {
			"type": "POST",
			"url": rootPath + '/user/queryUserIntegrals',
			// 默认为data，这里定义为demo
			"dataType":'json',
			"contentType": "application/json",
		    "data": function ( data ) {
		    	var uid = $("#uid").val();
		    	if(uid) {
		    		data.columns[0].search.value = $.trim(uid);
		    	} else {
		    		data.columns[0].search.value = "";
		    	}
		    	var uname = $("#uname").val();
		    	if(uname) {
		    		data.columns[1].search.value = $.trim(uname);
		    	} else {
		    		data.columns[1].search.value = "";
		    	}
		    	var realName = $("#realName").val();
		    	if(realName) {
		    		data.columns[2].search.value = $.trim(realName);
		    	} else {
		    		data.columns[2].search.value = "";
		    	}
		    	var phone = $("#phone").val();
		    	if(phone) {
		    		data.columns[3].search.value = $.trim(phone);
		    	} else {
		    		data.columns[3].search.value = "";
		    	}
		    	var sname = $("#sname").val();
		    	if(sname) {
		    		data.columns[4].search.value = $.trim(sname);
		    	} else {
		    		data.columns[4].search.value = "";
		    	}
		    	var rleIds = "";
		    	$('input:checkbox[name="rleId"]:checked').each(function(){
		    		rleIds += $(this).val() + ",";
		    	});
		    	rleIds = (rleIds != "") ? rleIds.substring(0,rleIds.length - 1) : "";
		    	data.columns[5].search.value = rleIds;
		    	return JSON.stringify(data);
		    },
		    error:function(){
		    	$("#refresh").click();
		    }
         
		},
		"columns" : [ {
			"name" : "uid",
			"data" : "uid",
			"orderable" : false,
		}, {
			"name" : "uname",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.uname?data.uname:"";
			},
			"orderable" : false,
		},  {
			"name" : "realName",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.realName?data.realName:"";
			},
			"orderable" : false,
		}, {
			"name" : "phone",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.phone?data.phone:"";
			},
			"orderable" : false,
		}, {
			"name" : "sname",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.sname?data.sname:"";
			},
			"orderable" : false,
		}, {
			"name" : "rleNames",
			"data" : null,
			"render" :function(data, type, row, meta) {
				if(data.rleIds == '20181529574197910125') {
					if(data.sid.substr(0,2) == "SQ") {
						return "社区梦想中心";
					} else {
						return "学校梦想中心"
					}
				}
				return data.rleNames?data.rleNames:"";
			},
			"orderable" : false,
		}, {
			"name" : "integral",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.integral!= null?data.integral:"";
			},
			"orderable" : false,
		},{
			"data" : null,
			"render": function (data,type,row,meta) {
				var tr = "";
				tr = "<a title='编辑用户积分' href='javascript:;' onclick='user_integral_edit(\"编辑用户积分\"," + "\"userIntegralEditPage?uid="
					 + data.uid + "\", \"\",\"\",\"\")' style='text-decoration:none'><i class='iconfont marginLeft12'>&#xe60a;</i></a></td>";
				return tr;
			},
			"orderable" : false,
			"searchable" : false,
		} ]
	});
	
	var CheckboxDropdown = function(el) {
        var _this = this;
        this.isOpen = false;
        this.areAllChecked = false;
        this.$el = $(el);
        this.$label = this.$el.find('.dropdown-label');
        this.$checkAll = this.$el.find('[data-toggle="check-all"]').first();
        this.$inputs = this.$el.find('[type="checkbox"]');

        this.onCheckBox();

        this.$label.on('click', function(e) {
            e.preventDefault();
            _this.toggleOpen();
        });

        this.$checkAll.on('click', function(e) {
            e.preventDefault();
            _this.onCheckAll();
        });

        this.$inputs.on('change', function(e) {
            _this.onCheckBox();
        });
    };

    CheckboxDropdown.prototype.onCheckBox = function() {
        this.updateStatus();
    };

    CheckboxDropdown.prototype.updateStatus = function() {
        var checked = this.$el.find(':checked');
        this.areAllChecked = false;
        this.$checkAll.html('全选');
        if (checked.length <= 0) {
            this.$label.html('角色');
        } else if (checked.length === this.$inputs.length) {
        	this.$label.html(checked.parent('label').text());
            this.areAllChecked = true;
            this.$checkAll.html('全不选');
        } else {
        	this.$label.html(checked.parent('label').text());
        }
    };

    CheckboxDropdown.prototype.onCheckAll = function(checkAll) {
        if (!this.areAllChecked || checkAll) {
            this.areAllChecked = true;
            this.$checkAll.html('Uncheck All');
            this.$inputs.prop('checked', true);
        } else {
            this.areAllChecked = false;
            this.$checkAll.html('Check All');
            this.$inputs.prop('checked', false);
        }
        this.updateStatus();
    };

    CheckboxDropdown.prototype.toggleOpen = function(forceOpen) {
        var _this = this;
        if (!this.isOpen || forceOpen) {
            this.isOpen = true;
            this.$el.addClass('on');
            $(document).on('click', function(e) {
                if (!$(e.target).closest('[data-control]').length) {
                    _this.toggleOpen();
                }
            });
        } else {
            this.isOpen = false;
            this.$el.removeClass('on');
            $(document).off('click');
        }
    };

    var checkboxesDropdowns = document.querySelectorAll('[data-control="checkbox-dropdown"]');
    for (var i = 0, length = checkboxesDropdowns.length; i < length; i++) {
        new CheckboxDropdown(checkboxesDropdowns[i]);
    }

	$("#searchUserIntegral").click(function() {
		$("#userIntegralTable").dataTable().fnClearTable();
	});
	$("#userIntegralTable").find('tbody').addClass('tableTR');
	//导出excel报表
	$("#export").click(function() {
		exportExcel(rootPath + "/user/exportUpdateUserIntegralsExcel");
	});
	
	layui.use('upload', function() {
		var upload = layui.upload; 
		//执行实例
		var uploadInst = upload.render({
			//绑定元素
			elem : '#import',
			//上传接口
			url : rootPath + "/user/importUpdateUserIntegrals",
			//指定允许上传时校验的文件类型
			accept : 'file',
			exts : 'xls|xlsx',
			before : function() {				
				layer.msg('可能需要一点时间,请耐心等待',{icon:6,time:1000});
			},
			done : function(res) {
				console.log(res);
				//上传完毕回调
				if (res.returnCode == "0000") {
					layer.alert('积分导入成功',function(index){
						layer.close(index);
						$("#searchUserIntegral").click();
					});
					
				} else {
					layer.alert(res.returnMessage);
				}
			},
			error : function() {
				//请求异常回调
				layer.alert("导入批量增减积分失败");
			}
		});
	});
});

function user_integral_edit(title, url, w, h) {
	layer_show(title, url, w, h);
}

function exportExcel(url, params) {
    // 创建form元素
    var temp_form = document.createElement("form");
    // 设置form属性
    temp_form.action = url;      
    temp_form.target = "_self";
    temp_form.method = "post";      
    temp_form.style.display = "none";
    // 处理需要传递的参数 
    for (var x in params) { 
        var opt = document.createElement("input");      
        opt.name = x;      
        opt.value = params[x];
        temp_form.appendChild(opt);      
    }      
    document.body.appendChild(temp_form);
    // 提交表单      
    temp_form.submit();
}